<?php

/**
 * 系统框架资源调度器
 * 
 * @author keluo<pycorvn@yeah.net>
 * @since 2015-01-24
 */
class SCScabish {
    
    const VERSION = 0;
    
    const SC_HTTP_404 = 10000404; // 404
    const SC_HTTP_500 = 10000500; // 500
    
    private static $_instance;
    
    private function __construct() {}
    
    public function __clone() {}
    
    public static function instance() {
        if(!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    
    /**
     * 运行框架
     * @throws Exception
     */
    public function run() {
        
        $this->buildEnvironment();
        
        $controller = SCS::request()->controller;
        
        try {
            $rc = new ReflectionClass($controller.'Controller');
        } catch (Exception $e) {
            try {
                $rc = new ReflectionClass('EmptyController'); 
            } catch (Exception $e) {
                throw new Exception('未定义的请求: '.$controller.
                    ', 当前请求: '.SCS::request()->requestURI, self::SC_HTTP_404);
            }
        }
        if(!$rc->isSubclassOf('SCController')) {
            throw new Exception('未定义的请求: '.$controller, self::SC_HTTP_404);
        }
        $action = SCS::request()->action;
        if(!$rc->hasMethod($action)) {
            if(!$rc->hasMethod('__empty')) {
                throw new Exception('未定义的方法: '.$action, self::SC_HTTP_404);
            } else {
                $action = '__empty';
            }
        }
        $class = $rc->newInstance();
        
        $method = $rc->getMethod($action);
        $params = self::checkMethod($method);
        $method->invokeArgs($class, $params);
    }
    
    /**
     * 初始化应用框架，构建应用环境
     */
    public function init() {
        $this->buildEnvironment();
        new SCProject;
    }
    
    /**
     * 构建框架运行环境
     */
    private function buildEnvironment() {
        date_default_timezone_set('PRC');
         
        /**
         * 加载自动加载类
        */
        require SC_SYS_CORE_PATH.'/SCAutoloader.class.php';
         
        /**
         * 注册类自动加载机制
         */
        spl_autoload_register(array('SCAutoloader', 'loadClass'));
        
        /**
         * 错误异常捕捉处理
         * 屏蔽所有页面报错信息，信息被透明捕获到异常处理类进行友好处理
        */
        error_reporting(0);
        ini_set('display_errors', 'On');
        
        set_error_handler('SCError::errorHandler', E_ALL);
        set_exception_handler('SCError::exceptionHandler');
        register_shutdown_function('SCError::fatalHandler');
        
    }
    
    /**
     * 检查方法所需参数
     * @param object $method
     * @return array 参数结果集
     */
    private function checkMethod($method) {
        $params = $method->getParameters();
        if(empty($params)) return array();
        $values = array();
        foreach($params as $param) {
            if($param->isDefaultValueAvailable()) {
                if(false === SCS::request()->param($param->getName())) {
                    $values[] = null;
                } else {
                    $values[] = SCS::request()->param($param->getName());
                }
            } else {
                if(!array_key_exists($param->getName(), SCS::request()->param())) {
                    throw new Exception('调用方法 '.$method->name.' 缺少参数：'.$param->getName(), E_USER_ERROR);
                }
                $values[] = SCS::request()->param($param->getName());
            }
        }
        return $values;
    }
    
    public function __destruct() {
        
    }
}